#!/bin/bash -e

# SPDX-FileCopyrightText: Red Hat, Inc.
# SPDX-License-Identifier: GPL-2.0-or-later

VDSM_CA="$1"
VDSM_KEY="$2"
VDSM_CRT="$3"

VDSM_TEMPLATE="$(mktemp)"

VDSM_FQDN=`hostname -f`
[ -z "$VDSM_FQDN" ] && VDSM_FQDN="localhost.localdomain"

VDSM_PERMS="@VDSMUSER@:@VDSMGROUP@"

umask 077

ACTIVATION_DATE=$(date -d yesterday -u +"%Y-%m-%d %H:%M:%S-0000")

if [ ! -f "$VDSM_KEY" ]; then
    /usr/bin/certtool --generate-privkey --outfile "$VDSM_KEY" 2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_KEY"
    /sbin/restorecon "$VDSM_KEY"
fi

if [ ! -f "$VDSM_CA" ]; then
    /bin/cat > "$VDSM_TEMPLATE" <<EOF
cn = "VDSM Certificate Authority"
ca
activation_date = "$ACTIVATION_DATE"
cert_signing_key
EOF
    /usr/bin/certtool --generate-self-signed --load-privkey  "$VDSM_KEY" \
                      --template "$VDSM_TEMPLATE" --outfile "$VDSM_CA" \
                      2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_CA"
    /sbin/restorecon "$VDSM_CA"
fi

if [ ! -f "$VDSM_CRT" ]; then
    /bin/cat > "$VDSM_TEMPLATE" <<EOF
organization    = "VDSM Certificate"
cn              = "$VDSM_FQDN"
email           = "root@$VDSM_FQDN"
activation_date = "$ACTIVATION_DATE"
signing_key
encryption_key
tls_www_server
tls_www_client
EOF
    /usr/bin/certtool --generate-certificate --load-privkey "$VDSM_KEY" \
                      --load-ca-privkey "$VDSM_KEY" \
                      --load-ca-certificate "$VDSM_CA" \
                      --template "$VDSM_TEMPLATE" --outfile "$VDSM_CRT" \
                      2> /dev/null
    /bin/chown "$VDSM_PERMS" "$VDSM_CRT"
    /sbin/restorecon "$VDSM_CRT"
fi

/bin/rm -f "$VDSM_TEMPLATE"
